# 服务器域名
ARG SERVER_NAME=vpn.example.com
# VPN账号
ARG USERNAME=admin
ARG PASSWORD=123456

# 构建阶段 - 证书生成
FROM buildpack-deps:bullseye AS build-certs

ARG SERVER_NAME
ENV SERVER_NAME=$SERVER_NAME

WORKDIR /home

RUN \
    # 下载pki
    apt update && yes | apt install strongswan-pki && \
    # 创建根证书（自签）和密钥
    pki --gen --type rsa --size 4096 --outform pem > server-root-key.pem && \
    pki --self --ca --lifetime 3650 \
    --in server-root-key.pem \
    --type rsa --dn "C=US, O=VPN Server, CN=VPN Server Root CA" \
    --outform pem > server-root-ca.pem && \
    # 创建服务器证书和密钥
    pki --gen --type rsa --size 4096 --outform pem > vpn-server-key.pem && \
    pki --pub --in vpn-server-key.pem \
    --type rsa | pki --issue --lifetime 1825 \
    --cacert server-root-ca.pem \
    --cakey server-root-key.pem \
    --dn "C=US, O=VPN Server, CN=$SERVER_NAME" \
    --san $SERVER_NAME \
    --flag serverAuth --flag ikeIntermediate \
    --outform pem > vpn-server-cert.pem


# 构建阶段 - 构建镜像
FROM mberner/strongswan:5.8.4

ARG SERVER_NAME
ARG USERNAME
ARG PASSWORD
ENV SERVER_NAME=$SERVER_NAME
ENV USERNAME=$USERNAME
ENV PASSWORD=$PASSWORD

WORKDIR /home

# 证书相关
COPY --from=build-certs /home/* /home/
RUN \
    # 拷贝服务器证书和密钥
    mkdir -p /etc/ipsec.d/certs && mkdir -p /etc/ipsec.d/private && \
    cp ./vpn-server-cert.pem /etc/ipsec.d/certs/vpn-server-cert.pem && \
    cp ./vpn-server-key.pem /etc/ipsec.d/private/vpn-server-key.pem

# VPN配置
COPY ipsec.conf /etc/ipsec.conf
RUN sed -i "s/server_name_or_ip/$SERVER_NAME/g" /etc/ipsec.conf

# VPN认证配置
COPY ipsec.secrets /etc/ipsec.secrets
RUN sed -i "s/server_name_or_ip/$SERVER_NAME/g" /etc/ipsec.secrets && \
    sed -i "s/your_username/$USERNAME/g" /etc/ipsec.secrets && \
    sed -i "s/your_password/$PASSWORD/g" /etc/ipsec.secrets

# Expose IKE and NAT-T ports
EXPOSE 4500/udp 500/udp

# 容器启动命令
ENTRYPOINT ["/bin/sh", "-c"]
CMD ["/usr/libexec/ipsec/charon"]